import React, { useState } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  TextInput, 
  TouchableOpacity, 
  FlatList,
  ActivityIndicator,
  Keyboard
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { searchCity } from '../services/weatherService';

const SearchScreen = ({ navigation }) => {
  const [keyword, setKeyword] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 搜索城市
  const handleSearch = async () => {
    if (!keyword.trim()) return;
    
    try {
      setLoading(true);
      setError(null);
      Keyboard.dismiss();
      
      const response = await searchCity(keyword);
      
      if (response.code === '200') {
        setResults(response.location || []);
        if (response.location?.length === 0) {
          setError('未找到相关城市，请更换关键词');
        }
      } else {
        setError(`搜索失败: ${response.code}`);
      }
    } catch (err) {
      console.error('城市搜索失败:', err);
      setError('搜索失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 选择城市，跳转到天气详情页
  const handleSelectCity = (city) => {
    navigation.navigate('WeatherDetail', { 
      city: city,
      locationId: `${city.lat},${city.lon}`
    });
  };

  // 渲染城市列表项
  const renderCityItem = ({ item }) => (
    <TouchableOpacity 
      style={styles.cityItem} 
      onPress={() => handleSelectCity(item)}
    >
      <View>
        <Text style={styles.cityName}>{item.name}</Text>
        <Text style={styles.cityInfo}>
          {item.adm2 && `${item.adm2}, `}{item.adm1}, {item.country}
        </Text>
      </View>
      <Ionicons name="chevron-forward" size={20} color="#999" />
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      {/* 搜索框 */}
      <View style={styles.searchContainer}>
        <View style={styles.searchInputContainer}>
          <Ionicons name="search" size={20} color="#999" style={styles.searchIcon} />
          <TextInput
            style={styles.searchInput}
            placeholder="输入城市名称"
            value={keyword}
            onChangeText={setKeyword}
            returnKeyType="search"
            onSubmitEditing={handleSearch}
            autoFocus={true}
          />
          {keyword.length > 0 && (
            <TouchableOpacity onPress={() => setKeyword('')}>
              <Ionicons name="close-circle" size={20} color="#999" />
            </TouchableOpacity>
          )}
        </View>
        <TouchableOpacity style={styles.searchButton} onPress={handleSearch}>
          <Text style={styles.searchButtonText}>搜索</Text>
        </TouchableOpacity>
      </View>

      {/* 搜索结果 */}
      {loading ? (
        <View style={styles.centerContainer}>
          <ActivityIndicator size="large" color="#0080ff" />
          <Text style={styles.loadingText}>搜索中...</Text>
        </View>
      ) : error ? (
        <View style={styles.centerContainer}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      ) : results.length > 0 ? (
        <FlatList
          data={results}
          renderItem={renderCityItem}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.resultsList}
        />
      ) : (
        <View style={styles.centerContainer}>
          <Ionicons name="search" size={64} color="#ddd" />
          <Text style={styles.placeholderText}>搜索全球城市天气</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  searchContainer: {
    flexDirection: 'row',
    padding: 15,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  searchInputContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
    borderRadius: 8,
    paddingHorizontal: 10,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    height: 40,
    fontSize: 16,
  },
  searchButton: {
    marginLeft: 10,
    paddingVertical: 8,
    paddingHorizontal: 15,
    backgroundColor: '#0080ff',
    borderRadius: 8,
  },
  searchButtonText: {
    color: '#fff',
    fontSize: 16,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
  },
  errorText: {
    fontSize: 16,
    color: '#ff6b6b',
    textAlign: 'center',
    paddingHorizontal: 30,
  },
  placeholderText: {
    marginTop: 10,
    fontSize: 16,
    color: '#999',
  },
  resultsList: {
    paddingVertical: 10,
  },
  cityItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#fff',
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  cityName: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
  },
  cityInfo: {
    fontSize: 14,
    color: '#999',
    marginTop: 3,
  },
});

export default SearchScreen;